<template>
  <div>
    <div class="flex justify-between pt-2 items-center">
      <div>
        <Checkbox
          v-model:checked="state.checkAll"
          :indeterminate="state.indeterminate"
          @change="onCheckAllChange"
          v-if="plainOptions.length"
        >
          全选
        </Checkbox>
      </div>
      <div>
        <RedoOutlined class="mr-2 cursor-pointer" @click="handleClickKey" title="刷新" />
        <Dropdown :trigger="['hover']" :overlayStyle="{ width: '50px', minWidth: '50px' }">
          <down-outlined />
          <template #overlay>
            <Menu>
              <MenuItem key="1" @click.stop="handleCreate">
                <plus-outlined class="cursor-pointer mr-2" title="新增" />
              </MenuItem>
              <MenuItem key="2" @click.stop="handleDelete" v-if="checkedList.length">
                <close-outlined class="cursor-pointer" style="color: red" title="删除" />
              </MenuItem>
            </Menu>
          </template>
        </Dropdown>
      </div>
    </div>
    <Divider v-if="plainOptions.length" style="margin: 10px; width: 100%" />
    <CheckboxGroup
      v-model:value="checkedList"
      :options="plainOptions"
      style="display: flex; flex-direction: column"
    />
    <SelectUser @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, watch, ref, onMounted, h } from 'vue';
  import { Checkbox, Divider, Dropdown, Menu } from 'ant-design-vue';
  import { PlusOutlined, CloseOutlined, DownOutlined, RedoOutlined } from '@ant-design/icons-vue';
  import { SelectUser } from '/@/components/CustomComp';
  import { useModal } from '/@/components/Modal';
  import {
    getUserCreateFavorite,
    getUserListFavorite,
    getUserDelFavorite,
  } from '/@/api/administration/administration';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  export default defineComponent({
    components: {
      Checkbox,
      CheckboxGroup: Checkbox.Group,
      Divider,
      PlusOutlined,
      CloseOutlined,
      SelectUser,
      DownOutlined,
      Dropdown,
      Menu,
      MenuItem: Menu.Item,
      RedoOutlined,
    },
    emits: ['change', 'handleClickKey', 'update:modelValue'],
    setup(props, { emit }) {
      const { t } = useI18n();
      const { createMessage, createConfirm } = useMessage();
      const plainOptions = ref<Recordable[]>([]);
      const checkedList = ref<Recordable[]>([]);
      let users = [];
      const state = ref<Recordable>({
        indeterminate: false,
        checkAll: false,
      });

      const onCheckAllChange = (e: any) => {
        checkedList.value = e.target.checked ? plainOptions.value.map((item) => item.value) : [];
        state.value.indeterminate = false;
      };
      watch(
        () => checkedList.value,
        (val) => {
          state.value.indeterminate = !!val.length && val.length < plainOptions.value.length;
          state.value.checkAll =
            val.length === plainOptions.value.length && plainOptions.value.length != 0;

          users = plainOptions.value
            .filter((item) => checkedList.value.includes(item.id))
            .map((el) => el.item);

          emit('update:modelValue', users.join(','));
          emit('change', users);
        },
      );

      const [registerModal, { openModal }] = useModal();
      function handleCreate() {
        openModal(true, {
          isUpdate: false,
          type: 'user',
        });
      }

      function handleSuccess(data) {
        if (data && data.length > 0) {
          const names = data.map((item) => item.name).join(',');
          save(names);
        }
      }
      const fetch = async () => {
        checkedList.value = [];
        plainOptions.value = (await getUserListFavorite()) || [];
        plainOptions.value.forEach((item) => {
          item.label = item.realName;
          item.value = item.id;
        });
        const values = plainOptions.value.map((item) => item.value);
        checkedList.value = values;

        // users = plainOptions.value
        //   .filter((item) => checkedList.value.includes(item.id))
        //   .map((el) => el.item);
      };
      const save = async (data) => {
        try {
          await getUserCreateFavorite({ items: data });
          await fetch();
          createMessage.success('新增成功');
        } catch (error) {
          console.error(error);
        }
      };
      onMounted(fetch);

      const handleDelete = () => {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要删除么'),
          onOk: async () => {
            try {
              await getUserDelFavorite({ ids: checkedList.value.join(',') });
              await fetch();
            } catch (err) {
              console.error(err);
            }
          },
        });
      };

      const getCheckedList = () => {
        return users;
      };

      const handleClickKey = () => {
        emit('handleClickKey');
      };
      return {
        state,
        plainOptions,
        onCheckAllChange,
        registerModal,
        handleCreate,
        handleSuccess,
        handleDelete,
        getCheckedList,
        checkedList,
        handleClickKey,
      };
    },
  });
</script>
